package ylg.com.cn.beuty.widget;

import android.content.Context;
import android.graphics.PointF;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;





import org.haitao.common.utils.PixelUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import ylg.com.cn.beuty.R;
import ylg.com.cn.beuty.main.adapter.NoticePagerAdapter;

/**
* @Description:this class is user for  viewpager play
* @author wang   
* @date 2015-8-28 上午11:32:58 
* @version V1.0   
*/
public class RunViewPager extends ViewPager {

    /** 触摸时按下的点 **/
    PointF downP = new PointF();
    /** 触摸时当前的点 **/
    PointF curP = new PointF();
    OnSingleTouchListener onSingleTouchListener;
    
	private int currentItem = 0;
	private ScheduledExecutorService scheduledExecutorService;
	private List<String> urls;
	private LinearLayout dot_ly;
	private Context context;
	private List<View> dots;
	private int oldPosition=0;

	private OnPageChangeListener onPageChangeListener;

	public RunViewPager(Context context) {
		super(context);
		this.context=context;
	}
	public RunViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context=context;
	}
	public List<String>  getData(){
		return this.urls;
	}

	public void  setData(int[] imges,LinearLayout dot_ly){

	}
	public void setData(List<String> urls,LinearLayout dot_ly){
		this.urls=urls;
		dots = new ArrayList<View>();
		if (dot_ly!=null) {
			dot_ly.removeAllViews();
			for(int i=0;i<urls.size();i++){
				View view =new View(context);
				int radius= PixelUtil.dp2px(context, 8);
				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( radius, radius);
				view.setLayoutParams(lp);
				view.setBackgroundResource(R.drawable.dot_round);
				lp.leftMargin= PixelUtil.dp2px(context, 8);
				dots.add(view);
				dot_ly.addView(view);
			}
		}

		RunViewPager.this.setAdapter(new NoticePagerAdapter(context,urls));
		// 设置预加载3 修复切换白屏bug
		RunViewPager.this.setOffscreenPageLimit(urls.size());
		setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				dots.get(oldPosition).setSelected(false);
				dots.get(position).setSelected(true);
				oldPosition = position;
				currentItem=position;
				if (onPageChangeListener!=null) {
					onPageChangeListener.onPageSelected(position);
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				if (onPageChangeListener!=null) {
					onPageChangeListener.onPageScrolled(arg0, arg1, arg2);
				}
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				if (onPageChangeListener!=null) {
					onPageChangeListener.onPageScrollStateChanged(arg0);
				}
			}
		});
		
	}

	/**
	 * 开始播放轮播
	 * @param speed
	 */
	public void startPlay(int speed){
		if (urls==null || urls.size()==0) {
			return;
		}
		if (scheduledExecutorService==null || scheduledExecutorService.isShutdown()) {
			scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
			// 当Activity显示出来后，每两秒钟切换一次图片显示
			scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 0, speed,TimeUnit.MILLISECONDS);
		}
	}

	public void startGo(int speed){
		if (scheduledExecutorService==null || scheduledExecutorService.isShutdown()) {
			scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
			// 当Activity显示出来后，每两秒钟切换一次图片显示
			scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 0, speed,TimeUnit.MILLISECONDS);
		}
	}
	/**
	 * 停止轮播 生命周期结束的时候一定要调用
	 */
	public void stopPlay(){
		if (scheduledExecutorService!=null) {
			
			scheduledExecutorService.shutdown();
		}
	}
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			setCurrentItem(currentItem, true);
		};
	};
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (RunViewPager.this) {
				currentItem = (currentItem + 1) % urls.size();
//				AppLog.e(""+(System.currentTimeMillis()-startTime ));
//				startTime = System.currentTimeMillis();
				handler.obtainMessage().sendToTarget();
			}
		}

	}
	public OnPageChangeListener getOnRunPageChangeListener() {
		return onPageChangeListener;
	}
	public void setOnnRunPageChangeListener(OnPageChangeListener onPageChangeListener) {
		this.onPageChangeListener = onPageChangeListener;
	}

    @Override
    public boolean onInterceptTouchEvent(MotionEvent arg0) {
        // 当拦截触摸事件到达此位置的时候，返回true，
        // 说明将onTouch拦截在此控件，进而执行此控件的onTouchEvent
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent arg0) {
        int x, y;
        // 每次进行onTouch事件都记录当前的按下的坐标
        curP.x = arg0.getX();
        curP.y = arg0.getY();

        if (arg0.getAction() == MotionEvent.ACTION_DOWN) {
            // 记录按下时候的坐标
            // 切记不可用 downP = curP ，这样在改变curP的时候，downP也会改变
            downP.x = arg0.getX();
            downP.y = arg0.getY();
            // 此句代码是为了通知他的父ViewPager现在进行的是本控件的操作，不要对我的操作进行干扰
            getParent().requestDisallowInterceptTouchEvent(true);
        }

        if (arg0.getAction() == MotionEvent.ACTION_MOVE) {
            // 此句代码是为了通知他的父ViewPager现在进行的是本控件的操作，不要对我的操作进行干扰
            x = (int)(curP.x - downP.x);
            y = (int)(curP.y - downP.y);
            int count = this.getAdapter().getCount()-1;
            if (Math.abs(x) > Math.abs(y)) {
                if (x > 0 && getCurrentItem() == 0) {// 第一页向左移动
                    getParent().requestDisallowInterceptTouchEvent(true);
                } else if (x < 0 && getCurrentItem() == count) {// 
                    getParent().requestDisallowInterceptTouchEvent(true);
                } else {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
            }else if(Math.abs(x) < Math.abs(y)) {
            	 getParent().requestDisallowInterceptTouchEvent(false);
            }

        }

        if (arg0.getAction() == MotionEvent.ACTION_UP) {
        	 getParent().requestDisallowInterceptTouchEvent(true);
            // 在up时判断是否按下和松手的坐标为一个点
            // 如果是一个点，将执行点击事件，这是我自己写的点击事件，而不是onclick
            if (downP.x == curP.x && downP.y == curP.y) {
                onSingleTouch();
                return false;
            }
        }
        if (arg0.getAction() == MotionEvent.ACTION_CANCEL) {
            getParent().requestDisallowInterceptTouchEvent(true);
        }
        return super.onTouchEvent(arg0);
    }

    /**
     * 单击
     */
    public void onSingleTouch() {
        if (onSingleTouchListener != null) {
            onSingleTouchListener.onSingleTouch();
        }
    }

    /**
     * 创建点击事件接口
     * 
     * @author wanpg
     * 
     */
    public interface OnSingleTouchListener {
        public void onSingleTouch();
    }

    public void setOnSingleTouchListener(
            OnSingleTouchListener onSingleTouchListener) {
        this.onSingleTouchListener = onSingleTouchListener;
    }
    
    /**
     * 默认3/4;
     */
    public void setDefaultHeight(){

    	int width = getScreenWidth(context);
    	int height = width*9/16;
    	getLayoutParams().height=height;
    }
    /**
     * 默认3/4;
     */
    public void setHeight(int height){
    	getLayoutParams().height=height;
    }
    /**
     * 获取屏幕宽度
     * @return the int
     */
    public  int getScreenWidth(Context activity) {
        // 获取屏幕密度（方法2） 
        DisplayMetrics dm = new DisplayMetrics(); 
        dm = activity.getResources().getDisplayMetrics(); 
        return  dm.widthPixels;      // 屏幕宽（像素，如：480px） 
    }
}
